//
//  DSYMusicViewController.m
//  BLDMusics
//
//  Created by dllo on 16/3/24.
//  Copyright © 2016年 李晓丹. All rights reserved.
//

#import "DSYMusicViewController.h"

@interface DSYMusicViewController ()<PlayerToolDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) DSYSongModel *currentMusic;

@property (nonatomic, retain) UILabel *songNameLabel;
@property (nonatomic, retain) UILabel *singerLabel;
@property (nonatomic, retain) UIImageView  *songImageView;

@property (nonatomic, retain) UIScrollView *lyricScrollView;
@property (nonatomic, retain) UITableView *lyricTableView;

@property (nonatomic, retain) UILabel *showProgressLabel;
@property (nonatomic, retain) UISlider *timeSlider;
@property (nonatomic, retain) UILabel *showTotalTime;

@property (nonatomic, retain) UISlider *soundSlider;

@property (nonatomic, retain) NSMutableArray *palyList;
@property (nonatomic, retain) UILabel *titleView;
@property (nonatomic, retain) UIButton *downLoadMusic;

@property (nonatomic, assign) NSInteger playStep;   /**< 播放步长 */
@property (nonatomic, assign) NSInteger playLoopStatus;  /**< 播放循环状态 */
@property (nonatomic, retain) UIButton *playLoopButton;  /**< 循环按钮 */

@property (nonatomic, retain) UIButton *searchLyriButton;  /**< 搜索歌词 */

@end

@implementation DSYMusicViewController

+ (instancetype)sharedMusicPlayingVC
{
    static DSYMusicViewController *musicPlayingVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        musicPlayingVC = [[DSYMusicViewController alloc] init];
    });
    return musicPlayingVC;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationController.navigationBar.translucent = YES;
    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor cyanColor] colorWithAlphaComponent:0.3]] forBarMetrics:UIBarMetricsDefault];
    
    [self addNavigationItem];
    
    _currentIndex = -2;
    // 开始是列表循环
    self.playLoopStatus = 0;
    self.playStep = 1;
    
    [DSYPlayerTool sharePlayerTool].delegate = self;
    
    [self creatSubviews];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    
    
    [super viewWillAppear:animated];
    if (_index == -1) {
        return;
    }
    
    
    if (_currentIndex == _index) {   // 在选择播放的下标和正在播放时相同的时候
        if (_index >= 0) {  // 如果当前选中的时候是大于
            DSYSongModel *modelIndex = [DSYDataManager shareDataManager].allDataArray[_index];
            
            DSYSongModel *modelCurrent = [DSYMusicViewController sharedMusicPlayingVC].currentMusic;
            
            if (modelIndex == modelCurrent) {  // 如果当前正在播放的音乐和选择要播放的音乐是相同的时候就不做任何操作
                return;
            }
        }
    }
    
    
    // 保存当前下标
    _currentIndex = _index;
    // 根据小标获取模型，显示信息，并播放音乐
    [self prepareForPlaying];
    
    self.navigationController.navigationBar.translucent = YES;
    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor cyanColor] colorWithAlphaComponent:0.3]] forBarMetrics:UIBarMetricsDefault];
    
    PlayViewController *bar = [PlayViewController sharePlayViewBar];
    [bar updateView];
    bar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{

    // 开启下载按钮的用户交互
    self.downLoadMusic.userInteractionEnabled = YES;
    
    [[PlayViewController sharePlayViewBar] updateView];
    PlayViewController *bar = [PlayViewController sharePlayViewBar];
    [bar updateView];
    bar.hidden = NO;
}

- (void)prepareForPlaying
{
    // 根据下标，获取模型

    _currentMusic = [DSYDataManager shareDataManager].allDataArray[_currentIndex];
    
    
    //
    if (_currentMusic.urlList.count <= 0 && self.isLocal == NO) {
        // 如果歌曲有问题就下一首
        [self nextAction:nil];
    }
    DSYUrlModel *model = [_currentMusic.urlList firstObject];
    
    // 播放音乐
    [[DSYPlayerTool sharePlayerTool] pause];
    
    if (_currentMusic.filename.length <= 0) {
        
        [[DSYPlayerTool sharePlayerTool] playWithUrl:model.url];
    } else {
        [[DSYPlayerTool sharePlayerTool] playWithLocalStr:_currentMusic.filename];
    }
    [[DSYPlayerTool sharePlayerTool] play];
    
    // 显示信息
    [self showSongInfo];
    
    
   
    [[DSYLyricTool shareLyricTool].lyricList removeAllObjects];
    [self.lyricTableView reloadData];
    
    // 加载歌词
    if (_currentMusic.lyric.length > 0) {

        [[DSYLyricTool shareLyricTool] loadLyricWithString:_currentMusic.lyric];
        [self.lyricTableView reloadData];
    } else {
        [[DSYLyricTool shareLyricTool].lyricList removeAllObjects];
        [self.lyricTableView reloadData];
    }
}

- (void)showSongInfo {
    _singerLabel.text = _currentMusic.singerName;
    
    if (_currentMusic.picUrl.length <= 0) {
        UIImage *image = [UIImage imageNamed:@"dsy_backgroun.jpg"];
        CGFloat imageW = image.size.width;
        CGFloat imageH = image.size.height;
        _songImageView.frame = CGRectMake(0, 0, SCREEN_HEIGTH * imageW / imageH, SCREEN_HEIGTH);
        _songImageView.center = self.view.center;
        
    } else {
        
        [_songImageView sd_setImageWithURL:[NSURL URLWithString:_currentMusic.picUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            CGFloat imageW = image.size.width;
            CGFloat imageH = image.size.height;
            _songImageView.frame = CGRectMake(0, 0, SCREEN_HEIGTH * imageW / imageH, SCREEN_HEIGTH);
            _songImageView.center = self.view.center;
            
        }];
    }
    
    
    NSInteger duration = [DSYPlayerTool sharePlayerTool].duration;
    _showTotalTime.text = [NSString stringWithFormat:@"%02ld:%02ld", duration / 60, duration % 60];
    self.titleView.text = [NSString stringWithFormat:@"%@--%@", _currentMusic.name, _currentMusic.singerName];
}

- (void)creatSubviews {
    
    self.songImageView = [[UIImageView alloc] init];
    [self.view addSubview:_songImageView];
    _songImageView.frame = self.view.frame;
    
    
    self.singerLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 64, 100, 30)];
    [self.view addSubview:_singerLabel];
    _singerLabel.textColor = [UIColor whiteColor];
    
    UIView *backgroundView =[[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 150, self.view.frame.size.width, 150)];
    [self.view addSubview:backgroundView];
    backgroundView.backgroundColor = [UIColor blackColor];
    backgroundView.alpha = 0.5;
    
    self.soundSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 100, 30)];
    _soundSlider.center = CGPointMake(self.view.center.x, _soundSlider.center.y);
    [backgroundView addSubview:_soundSlider];
    _soundSlider.value = 1.0;
    [_soundSlider addTarget:self action:@selector(soundSliderAction:) forControlEvents:UIControlEventValueChanged];
    
    self.downLoadMusic = [UIButton buttonWithType:UIButtonTypeCustom];
    _downLoadMusic.frame = CGRectMake(CGRectGetMaxX(_soundSlider.frame), CGRectGetMinY(_soundSlider.frame), 40, CGRectGetHeight(_soundSlider.frame));
    [_downLoadMusic setTitle:@"下载" forState:UIControlStateNormal];
    [_downLoadMusic setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [backgroundView addSubview:_downLoadMusic];
    _downLoadMusic.highlighted = YES;
    [_downLoadMusic addTarget:self action:@selector(downLoadAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.timeSlider = [[UISlider alloc] initWithFrame:CGRectMake( 0, CGRectGetMaxY(_soundSlider.frame) + 20, CGRectGetWidth(_soundSlider.frame), 30)];
    _timeSlider.center = CGPointMake(self.view.center.x, _timeSlider.center.y);
    [backgroundView addSubview:_timeSlider];
    [_timeSlider addTarget:self action:@selector(timeSliderAction:) forControlEvents:UIControlEventValueChanged];
    
    
    UIButton *playOrPauseButton = [UIButton buttonWithType:UIButtonTypeCustom];
    playOrPauseButton.frame = CGRectMake(0, 0, 100, 30);
    playOrPauseButton.center = CGPointMake(self.view.center.x, CGRectGetMaxY(_timeSlider.frame) + 20);
    playOrPauseButton.backgroundColor = [UIColor greenColor];
    [playOrPauseButton setTitle:@"播放/暂停" forState:UIControlStateNormal];
    [playOrPauseButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [backgroundView addSubview:playOrPauseButton];
    [playOrPauseButton addTarget:self action:@selector(playOrPauseAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *lastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    lastButton.frame = CGRectMake(0, 0, 80, 30);
    lastButton.center = CGPointMake(self.view.center.x - 100, playOrPauseButton.center.y);
    [lastButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [lastButton setTitle:@"上一首" forState:UIControlStateNormal];
    [backgroundView addSubview:lastButton];
    [lastButton addTarget:self action:@selector(lastAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.frame = CGRectMake(0, 0, 80, 30);
    nextButton.center = CGPointMake(self.view.center.x + 100, playOrPauseButton.center.y);
    [nextButton setTitle:@"下一首" forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [backgroundView addSubview:nextButton];
    [nextButton addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.searchLyriButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _searchLyriButton.frame = CGRectMake(CGRectGetMaxX(nextButton.frame) + 10, CGRectGetMinY(nextButton.frame), 40, CGRectGetHeight(nextButton.frame));
    [_searchLyriButton setTitle:@"歌词" forState:UIControlStateNormal];
    _searchLyriButton.highlighted = YES;
    [_searchLyriButton addTarget:self action:@selector(searchLyricAction:) forControlEvents:UIControlEventTouchUpInside];
    [backgroundView addSubview:_searchLyriButton];
    
    
    // 添加喇叭
    UIImageView *volumeImgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, CGRectGetMinY(_soundSlider.frame), 30, 30)];
    volumeImgView.image = [UIImage imageNamed:@"iconfont-volume"];
    [backgroundView addSubview:volumeImgView];
    
    self.showTotalTime = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_timeSlider.frame), CGRectGetMinY(_timeSlider.frame), 40, CGRectGetHeight(_timeSlider.frame))];
    _showTotalTime.font = [UIFont systemFontOfSize:13.0f];
    _showTotalTime.textColor = [UIColor redColor];
    _showTotalTime.text = @"--:--";
    [backgroundView addSubview:_showTotalTime];
    
    self.showProgressLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, CGRectGetMinY(_timeSlider.frame), 40, CGRectGetHeight(_timeSlider.frame))];
    _showProgressLabel.font = [UIFont systemFontOfSize:13.0f];
    _showProgressLabel.textColor = [UIColor redColor];
    _showProgressLabel.text = @"--:--";
    [backgroundView addSubview:_showProgressLabel];
    
    
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    
    self.titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width * 2 / 3, 40)];
    _titleView.font = [UIFont systemFontOfSize:17.0f];
    _titleView.textColor = [UIColor whiteColor];
    
    self.navigationItem.titleView = _titleView;
    
    
    self.playLoopButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playLoopButton.frame = CGRectMake(CGRectGetMinX(lastButton.frame) - 35, CGRectGetMinY(lastButton.frame), 35, CGRectGetHeight(lastButton.frame));
    [_playLoopButton setBackgroundImage:[UIImage imageNamed:@"iconfont-ttpodicon-3"] forState:UIControlStateNormal];
    [backgroundView addSubview:_playLoopButton];
    
    [_playLoopButton addTarget:self action:@selector(playLoopAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:self.lyricScrollView];
    
}

- (void)playOrPauseAction:(UIButton *)sender {
    if ([DSYPlayerTool sharePlayerTool].isPlaying == YES) {
        [[DSYPlayerTool sharePlayerTool] pause];
    } else {
        [[DSYPlayerTool sharePlayerTool] play];
    }
}

- (void)lastAction:(UIButton *)sender {

    _currentIndex = _currentIndex - self.playStep;
    
    if (self.playLoopStatus == 2) {  // 如果是随机播放的时候
        _currentIndex = _currentIndex % ([DSYDataManager shareDataManager].allDataArray.count);
        // 获取播放后再次产生随机数
        self.playStep = arc4random() % ([DSYDataManager shareDataManager].allDataArray.count + 1);
    }
    
    if (_currentIndex < 0) {
        _currentIndex = [DSYDataManager shareDataManager].allDataArray.count - 1;
    }
    [self prepareForPlaying];
    
    [[PlayViewController sharePlayViewBar] updateView];
}

- (void)nextAction:(UIButton *)sender {
    
    _currentIndex = _currentIndex + self.playStep;
    if (self.playLoopStatus == 2) {  // 如果是随机播放的时候
        _currentIndex = _currentIndex % ([DSYDataManager shareDataManager].allDataArray.count);
        // 获取播放后再次产生随机数
        self.playStep = arc4random() % ([DSYDataManager shareDataManager].allDataArray.count + 1);
    }
    
    
    if (_currentIndex == [DSYDataManager shareDataManager].allDataArray.count) {
        _currentIndex = 0;
    }
    [self prepareForPlaying];
    
    [[PlayViewController sharePlayViewBar] updateView];
}

- (void)timeSliderAction:(UISlider *)sender {
    [[DSYPlayerTool sharePlayerTool] seekToTime:sender.value * [DSYPlayerTool sharePlayerTool].duration];
    
}

- (void)soundSliderAction:(UISlider *)sender {
    [DSYPlayerTool sharePlayerTool].sound = sender.value;
    
    // 静音的显示
    if (sender.value == 0) {
        
    }
}


- (void)playingWithTime:(NSTimeInterval)time
{
    _timeSlider.value = time;
    
    NSInteger duration = [DSYPlayerTool sharePlayerTool].duration;
    NSInteger totalTiem = time * [DSYPlayerTool sharePlayerTool].duration;
    _showProgressLabel.text = [NSString stringWithFormat:@"%02ld:%02ld", totalTiem / 60, totalTiem % 60];
    _showTotalTime.text = [NSString stringWithFormat:@"%02ld:%02ld", duration / 60, duration % 60];
    
    
    if (_currentMusic.lyric.length <= 0) {
        return;
    }
    // 通过时间，获取小标
    NSInteger index = [[DSYLyricTool shareLyricTool] lyricIndexWithTime:time];
    
    
    if (index >= [DSYLyricTool shareLyricTool].lyricList.count) {
        return;
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self.lyricTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:(UITableViewScrollPositionMiddle)];
    
}

- (void)didStop
{
    [[DSYLyricTool shareLyricTool].lyricList removeAllObjects];
    
    [self nextAction:nil];
    [[PlayViewController sharePlayViewBar] updateView];
    
}

- (void)addNavigationItem {
    
    //    self.navigationItem.titleView =  self.paomaView;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"<<" style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    
}

- (void)back:(UIBarButtonItem *)backItem {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (UIImage *)imageWithColor:(UIColor *)color {
    
    // 描述矩形
    CGRect rect = CGRectMake(0, 0, 1, 1);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}


- (void)playLoopAction:(UIButton *)button {
    // 播放状态有三种
    self.playLoopStatus = (_playLoopStatus + 1) % 3;
    NSLog(@"%ld", self.playLoopStatus);
    NSString *backImgStr = @"";
    if (self.playLoopStatus == 0) {  // 列表循环
        backImgStr = @"iconfont-ttpodicon-3";
        self.playStep = 1;
    }
    if (self.playLoopStatus == 1) {  // 单曲循环
        backImgStr = @"iconfont-danquxunhuan";
        self.playStep = 0;
    }
    if (self.playLoopStatus == 2) {  // 随机播放
        backImgStr = @"iconfont-suijibofang";
        // 随机数
        self.playStep = arc4random() % ([DSYDataManager shareDataManager].allDataArray.count + 1);
    }
    
    [self.playLoopButton setBackgroundImage:[UIImage imageNamed:backImgStr] forState:UIControlStateNormal];
}


- (void)downLoadAction:(UIButton *)button {
    
    if (_currentMusic == nil) {
        return;
    }
    
    if (_currentMusic.filename.length > 0) {
        [DSYMessageHUD showAddToView:self.view withMessage:@"歌曲已经下载" animated:YES];
        return;
    }
    
    // 获取当前音乐的播放地址
    // 根据下标，获取模型
    _currentMusic = [DSYDataManager shareDataManager].allDataArray[_currentIndex];
    
    // 从plist中查找是否有下载过的歌曲
    NSMutableArray *songPlist = [[DSYDataManager shareDataManager] getPlist];
    for (DSYSongModel *songModel  in songPlist) {
        BOOL condition = [songModel.name isEqualToString:_currentMusic.name] && [songModel.singerName isEqualToString:_currentMusic.singerName] && [songModel.picUrl isEqualToString:_currentMusic.picUrl];
        if (condition) {  // 如果相同就提示已经下载过
            [DSYMessageHUD showAddToView:self.view withMessage:@"歌曲已经下载" animated:YES];
            return;
        }
    }
    
    //
    if (_currentMusic.urlList.count <= 0) {
        // 如果歌曲有问题就下一首
        [self nextAction:nil];
    }
    DSYUrlModel *model = [_currentMusic.urlList firstObject];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:model.url]];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *man = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    self.downLoadMusic.userInteractionEnabled = NO;
    NSURLSessionDownloadTask *downloadTask = [man downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
        
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        
        // 单例0
        NSFileManager *filemanager = [NSFileManager defaultManager];
        // 文件管理器创建创建一个文件夹
        // 1. 获取沙盒路径
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        // 2. 拼接路径
        NSString *songsPath = [documentPath stringByAppendingPathComponent:@"songs"];
        if (![filemanager fileExistsAtPath:songsPath]) {
            
            [filemanager createDirectoryAtPath:songsPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        
        documentsDirectoryURL = [documentsDirectoryURL URLByAppendingPathComponent:@"songs"];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        
        
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *plistPath = [documentPath stringByAppendingPathComponent:@"songList.plist"];
        
        NSArray *plistArr = [NSArray arrayWithContentsOfFile:plistPath];
        // 解析出来数据
        
        NSString *file = filePath.absoluteString;
        
        NSArray *fileArr = [file componentsSeparatedByString:@"/"];
        
        NSMutableArray *songList = [NSMutableArray arrayWithArray:plistArr];
        NSMutableDictionary *songDictionary = [NSMutableDictionary dictionary];
        
        
        [songDictionary setObject:self.currentMusic.name forKey:@"name"];
        [songDictionary setObject:[fileArr lastObject] forKey:@"filename"];
        [songDictionary setObject:self.currentMusic.picUrl forKey:@"picUrl"];
        [songDictionary setObject:self.currentMusic.singerName forKey:@"singerName"];
        
        // 将下载来的东西放到数组中
        [songList addObject:songDictionary];
        
        [songList writeToFile:plistPath atomically:YES];
        
        [DSYMessageHUD showAddToView:self.view withMessage:@"歌曲成功下载" animated:YES];
        
        self.downLoadMusic.userInteractionEnabled = YES;
    }];
    
    [downloadTask resume];
}

- (UIScrollView *)lyricScrollView
{
    if (!_lyricScrollView) {
        self.lyricScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGTH - 214)];
        
        self.lyricScrollView.backgroundColor = [UIColor clearColor];
        self.lyricScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, SCREEN_HEIGTH - 214);
        
        self.lyricTableView = [[UITableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, CGRectGetHeight(_lyricScrollView.frame)) style:UITableViewStylePlain];
        _lyricTableView.delegate = self;
        [_lyricTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tableViewCell"];
        _lyricTableView.backgroundColor = [UIColor clearColor];
        _lyricTableView.delegate = self;
        _lyricTableView.dataSource = self;
        _lyricTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.lyricScrollView addSubview:_lyricTableView];
        
    }
    return _lyricScrollView;
}

#pragma mark - tableView的dataSource和delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"];
    
    
    DSYLyric *lyric = [DSYLyricTool shareLyricTool].lyricList[indexPath.row];
    
    cell.textLabel.text = lyric.string;
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.highlightedTextColor = [UIColor redColor];
    
    cell.selectedBackgroundView = ({UIView *view = [[UIView alloc] init]; view;});
    
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [DSYLyricTool shareLyricTool].lyricList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DSYLyric *lyric = [DSYLyricTool shareLyricTool].lyricList[indexPath.row];
    
    CGSize size = [APPTools labelRectWithSize:CGSizeMake(self.view.frame.size.width, 0) labelText:lyric.string Font:[UIFont systemFontOfSize:21.0]];
    return size.height + 17;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    DSYLyric *lyric = [DSYLyricTool shareLyricTool].lyricList[indexPath.row];
    
    // 获取歌词的时间
    NSTimeInterval currentTimeScale = lyric.time / [DSYPlayerTool sharePlayerTool].duration;
    
    self.timeSlider.value =  currentTimeScale;
    
    [self timeSliderAction:self.timeSlider];
}

#pragma mark - 搜索歌词
- (void)searchLyricAction:(UIButton *)button {
//    [[DSYLyricTool shareLyricTool] loadLyricWithString:@""];
    
//    NSString *urlStr = [NSString stringWithFormat:@"http://search.dongting.com/lyric/search?sign=70f7cf90f3553d44d094b89ecb288f89&title=%@&song_id=%@&artist=%@", self.currentMusic.name, self.currentMusic.songId, self.currentMusic.singerName];
//    
//    NSLog(@"%@", urlStr);
//    [APPTools GETWithURL:urlStr par:nil success:^(id responseObject) {
//        
//        NSLog(@"%@", responseObject);
//        
//    } filed:^(NSError *error) {
//        
//    }];
//    [[DSYLyricTool shareLyricTool] loadLyricWithString:_currentMusic.lyric];
//    [self.lyricTableView reloadData];
    
    
}



@end
